package com.icookie.shuatim.api.service;

import com.shuatim.common.enums.CustomHttpStatus;
import com.shuatim.common.exception.ShuaTiException;
import com.shuatim.model.wechat.User;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author : issuser ✌️
 * @date : 2019/4/18 16:27
 */
public abstract class AbstractService {
    /**
     * //用户会话关键字
     */
    private static final String SESSION_USER_KEY = "SESSION_USER_KEY";

    @Resource
    protected HttpServletRequest request;


    protected User currentUser() {
        HttpSession session = getSession(false);

        if (session != null) {
            User userInfo = (User) session.getAttribute(SESSION_USER_KEY);
            if (userInfo != null && userInfo.getId() != null) {
                return userInfo;
            }
        }
        throw new ShuaTiException(CustomHttpStatus.USER_NOT_LOGIN);
    }

    protected User currentUserWithoutException() {
        HttpSession session = getSession(false);
        User userInfo = null;
        if (session != null) {
            userInfo = (User) session.getAttribute(SESSION_USER_KEY);
        }

        return userInfo;
    }

    protected void addUserToSession(User userInfo) {
        request.getSession().setAttribute(SESSION_USER_KEY, userInfo);
    }

    protected Long currentUserId() {
        return currentUser().getId();
    }

    /**
     * 获取session对象
     */
    protected HttpSession getSession(boolean create) {
        return request.getSession(create);
    }

    /**
     * 获取request对象
     *
     * @return
     */
    public HttpServletRequest getRequest() {
        return request;
    }

    // @InitBinder
    // protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
    //     //对于需要转换为Date类型的属性，使用DateEditor进行处理
    //     binder.registerCustomEditor(Date.class, new DateEditor());
    // }

}
